package com.ryskoo.framework.core.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableCaching
// 启用缓存，这个注解很重要；
// 继承CachingConfigurerSupport，为了自定义生成KEY的策略。可以不继承。
public class RedisConfig extends CachingConfigurerSupport {

	// /**
	// * 缓存管理器.
	// *
	// * @param redisTemplate
	// * @return
	// */
	// @Bean
	// public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
	// CacheManager cacheManager = new RedisCacheManager(redisTemplate);
	// return cacheManager;
	// }
	//
	// @Bean
	// public RedisTemplate<Serializable, Serializable> redisTemplate(
	// JedisConnectionFactory redisConnectionFactory) {
	// RedisTemplate<Serializable, Serializable> redisTemplate = new
	// RedisTemplate<Serializable, Serializable>();
	// // key序列化方式;（不然会出现乱码;）,但是如果方法上有Long等非String类型的话，会报类型转换错误；
	// // 所以在没有自己定义key生成策略的时候，以下这个代码建议不要这么写，可以不配置或者自己实现
	// // ObjectRedisSerializer
	// // 或者JdkSerializationRedisSerializer序列化方式;
	// redisTemplate.setKeySerializer(new StringRedisSerializer());
	// redisTemplate.setHashKeySerializer(new StringRedisSerializer());
	// redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
	// redisTemplate
	// .setHashValueSerializer(new JdkSerializationRedisSerializer());
	//
	// // 以上4条配置可以不用
	// redisTemplate.setConnectionFactory(redisConnectionFactory);
	// return redisTemplate;
	// }

	@Bean
	@ConfigurationProperties(prefix = "spring.redis")
	public JedisPoolConfig getRedisConfig() {
		JedisPoolConfig config = new JedisPoolConfig();
		return config;
	}

	@Bean
	@ConfigurationProperties(prefix = "spring.redis")
	public JedisConnectionFactory getConnectionFactory() {
		JedisConnectionFactory factory = new JedisConnectionFactory();
		JedisPoolConfig config = getRedisConfig();
		factory.setPoolConfig(config);
		return factory;
	}

	@Bean
	public RedisTemplate<?, ?> getRedisTemplate() {
		RedisTemplate<?, ?> template = new StringRedisTemplate(getConnectionFactory());
		return template;
	}

}
